<?php
/**
 * Created by PhpStorm.
 * User: Jason
 * Date: 2017/9/22
 * Time: 15:28
 */

namespace Home\Service;


use Common\Util\HttpClient;
use Think\Model;

class UserService extends Model
{
    protected $name = 'user';


    public function getRandomUser()
    {
        $list = M('User')->order('rand()')->limit(7)->select();
        return $list;
    }

    /*
     * 更新或添加登录用户信息
     */
    public function addUser($param)
    {
        //通过unionid查询用户信息是否存在
        $userExist = M('User')->where(array('union_id'=>$param['unionid']))->find();

        $userInfo = $this->wxGetUserInfo($param['access_token'], $param['openid']);
        //重组数组
        $userInfo['open_id'] = $userInfo['openid'];
        $userInfo['union_id'] = $userInfo['unionid'];
        $userInfo['avatar_url'] = $userInfo['headimgurl'];
        $userInfo['gender'] = $userInfo['sex'];

        if (!empty($userExist)) {

            $userInfo['update_time'] = date('Y-m-d H:i:s', time());
            M('User')->where(array('union_id' => $param['unionid']))->save($userInfo);
            $userInfo['uid'] = $userExist['id'];
        } else {
            //添加新用户记录
            $id = M('User')->add($userInfo);
            $userInfo['uid'] = $id;
        }

        //todo 更新今日登录用户记录

        return $userInfo;
    }

    /*
     * 获取web微信登录用户信息
     */
    private function wxGetUserInfo($accessToken, $openid)
    {
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$accessToken.'&openid='.$openid;
        $returnInfo = json_decode(HttpClient::get($url), true);
        return $returnInfo;
    }

    /**
     * 获取用户基本信息
     */
    public function userinfoByIds($userIds)
    {
        $map = [
            'id' => ['in', $userIds]
        ];
        $list = $this->field('id, nickname, avatar_url')->where($map)->select();
        if (!$list) {
            return [];
        }
        $userMap = [];
        foreach ($list as $key => $val) {
            $userMap[$val['id']] = $val;
        }
        return $userMap;
    }

}